# -*- coding: utf-8 -*-
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# 易付
APP_CONF = {
    '201831067175': {  # 亿付支付 2.5% 100---5万 测试环境
        'APP_KEY': '0a758c8dbb4f58aefbc348c9d66cd802',
        'APP_SECRET': 'xIsWR8ieQL5OikAjKxH3fScomAsVBjRD',
        'auth': 'https://api.eferpay.com/oss/auth/login',
        'pay_channel': 'https://api.eferpay.com/oss/wallet/getCrepayChannelList',
        'gateway': 'https://api.eferpay.com/oss/wallet/crepayOrder',
    },
    '201817430050': {  # 亿付支付 1.6% 100-49999 zs
        'APP_KEY': '5b64262d0b5e0417396d2fe9f079078b',
        'APP_SECRET': 'D6ZCMK0A66CO4DYhbBKEL9I6AE41ynDX',
        'auth': 'https://oss.eferpay.com/oss/auth/login',
        'pay_channel': 'https://oss.eferpay.com/oss/wallet/getCrepayChannelList',
        'gateway': 'https://oss.eferpay.com/oss/wallet/crepayOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['APP_KEY']


def _get_appSecret(mch_id):
    return APP_CONF[mch_id]['APP_SECRET']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_auth(mch_id):
    return APP_CONF[mch_id]['auth']


def _get_pay_channel(mch_id):
    return APP_CONF[mch_id]['pay_channel']


def generate_auth_sign(d, key):
    s = 'appId={}&appSecret={}&appSpbillIp={}&appToken={}&appVersion={}&{}'.format(d['appId'], d['appSecret'],
                                                                                   d['appSpbillIp'], d['appToken'],
                                                                                   d['appVersion'],
                                                                                   key)
    return str_sha1_encrypt(s)


def generate_sign(d_h, d_c, key):
    s = 'appId={}&appSecret={}&appSpbillIp={}&appToken={}&appVersion={}&channelType={}&orderMoney={}&orderNotify={' \
        '}&orderReturl={}&orderTradeSn={}&{}'.format(
        d_h['appId'], d_h['appSecret'],
        d_h['appSpbillIp'], d_h['appToken'],
        d_h['appVersion'], d_c['channelType'], d_c['orderMoney'], d_c['orderNotify'], d_c['orderReturl'],
        d_c['orderTradeSn'],
        key)
    return str_sha1_encrypt(s)


def generate_notify_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += '{}'.format(key)
    return str_sha1_encrypt(s)


def verify_notify_sign(params, key):
    params.pop('orderStatus')
    sign = params.pop('appSign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yifu2pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """ 支付宝手机网页支付:1
        支付宝转账支付:2 """
    if service == 'cloud_flash':
        return 'unionpay'
    elif service == 'alipay':
        return 'alipay'
    return '云闪付'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def str_sha1_encrypt(str):
    """
    使用sha1加密算法，返回str加密后的字符串
    """
    sha = hashlib.sha1(str)
    encrypts = sha.hexdigest()
    return encrypts


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']

    d_header = OrderedDict((
        ('cache-control', 'no-cache'),
        ('content-type', 'application/x-www-form-urlencoded'),
        ('appVersion', '1.0.0'),
        ('appId', app_id),
        ('appSecret', _get_appSecret(app_id)),
        ('appSpbillIp', _get_device_ip(info)),
        ('appToken', str_sha1_encrypt(app_id + _get_appSecret(app_id) + api_key)),
    ))
    d_header['appSign'] = generate_auth_sign(d_header, api_key)
    auth_response = requests.post(_get_auth(app_id), headers=d_header, timeout=5)
    user_token = json.loads(auth_response.text)['data']['userToken']
    d_header['appToken'] = user_token
    d_header['appSign'] = generate_auth_sign(d_header, api_key)
    pay_channel_response = requests.post(_get_pay_channel(app_id), headers=d_header, timeout=5)
    for channel in json.loads(pay_channel_response.text)['data']:
        if str(channel['channelCode'].encode('utf-8')) == _get_pay_type(service):
            channelType = channel['channelType']
    d_header['appToken'] = user_token
    create_data = OrderedDict((
        ('channelType', str(channelType)),
        ('orderMoney', '%.2f' % pay_amount),
        ('orderTradeSn', str(pay.id)),
        ('orderNotify', urllib.quote_plus(
            '{}/pay/api/{}/yifu2pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)).lower()),
        ('orderReturl', urllib.quote_plus(
            '{}/pay/api/{}/yifu2pay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)).lower()),
    ))
    d_header['appSign'] = generate_sign(d_header, create_data, api_key)
    _LOGGER.info("yifu2pay create header is: %s", json.dumps(d_header))
    _LOGGER.info("yifu2pay create body is: %s", json.dumps(create_data))
    create_response = requests.post(_get_gateway(app_id), headers=d_header, data=create_data, timeout=5)
    _LOGGER.info("yifu2pay create: %s", create_response.text)
    data = json.loads(create_response.text)['data']

    if service == 'cloud_flash':
        template_data = {'base64_img': data['orderQrcode'], 'amount': pay_amount,
                         'order_id': create_data['orderTradeSn'], 'due_time': int(time.time()) + 180}
        t = get_template('cloud_flash_yifu2pay.html')

        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("yifu2pay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    elif service == 'alipay':
        return {'charge_info': data['orderPayurl']}

    # 对方支付宝收银台做的比较好，使用他们的收银台，自己的也先放着

    # elif service == 'alipay':
    #     template_data = {'base64_img': data['orderQrcode'], 'amount': pay_amount}
    #     t = get_template('qr_alipay_yifu2pay.html')
    # html = t.render(Context(template_data))
    # cache_id = redis_cache.save_html(pay.id, html)
    # _LOGGER.info("yifu2pay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    # return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("yifu2pay notify data: %s, order_id is: %s", data, data['orderTradeSn'])
    verify_notify_sign(data, api_key)
    pay_id = data['orderTradeSn']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yifu2pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['orderState'])
    trade_no = data['orderSn']
    total_fee = float(data['orderMoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 订单状态 0表示待付款 1表示已付款待确认 2表示支付失效 3表示支付成功
    if trade_status == '3' and total_fee > 0.0:
        _LOGGER.info('yifu2pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pass
